package com.daoliuhe.scaffold.service.impl;

import com.daoliuhe.scaffold.mapper.ListNameMapper;
import com.daoliuhe.scaffold.model.ListName;
import com.daoliuhe.scaffold.service.ListNameService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class ListNameServiceImpl implements ListNameService {

	private static final Logger logger = LoggerFactory.getLogger(ListNameServiceImpl.class);
	@Autowired
	ListNameMapper listNameMapper;

	@Override
	public ListName getById(String id) {
		logger.info("getById,id:{}",id);
		return listNameMapper.selectByPrimaryKey(id);
	}

	@Override
	public ListName selectByApiName(String apiName) {
		logger.info("selectByApiName,apiName:{}",apiName);
		return listNameMapper.selectByApiName(apiName);
	}

	@Override
	public void saveOrUpdate(ListName entity) {
		logger.info("saveOrUpdate,entity:{}",entity);
		if (!StringUtils.isEmpty(entity.getId())) {
			listNameMapper.updateByPrimaryKeySelective(entity);
		} else {
			listNameMapper.insert(entity);
		}
	}
	
	@Override
	public Map<String, Object> getPageData(ListName entity) {
		logger.info("getPageData,entity:{}",entity);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("total", listNameMapper.getPageCount(entity));
		map.put("rows", listNameMapper.getPageData(entity));
		return map;
	}
	
	@Override
	public boolean vApiName(ListName entity) {
		logger.info("vApiName,entity:{}",entity);
		boolean success = true;
		ListName listName = listNameMapper.selectByApiName(entity.getApiName());
		if (listName != null) {
			String id = entity.getId();
			// 新增对象时，如果数据库中已经存在有apiName的数据，则提示重复
			if (StringUtils.isEmpty(id)) {
				success = false;
			} else {
				// 修改对象时，如果数据库中已经存在与填写apiName的数据一样且id不一致，则提示重复
				if (!listName.getId().equals(id)) {
					success = false;
				}
			}
		}
		return success;
	}
	
}
